<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.username" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loaddata">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleadd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--
            列表
                selection-change：当用户勾选或者取消勾选前面的多选框的时候，触发事件
                    事件函数有一个参数：参数是 当勾选或者取消勾选后，剩下的所有被勾选的行，放在数组中
        -->
        <el-table :data="employees" highlight-current-row v-loading="listloading" stripe border size="mini"
                  @selection-change="selschange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="username" label="名称"  sortable></el-table-column>
            <el-table-column prop="email" label="邮箱"  sortable></el-table-column>
            <el-table-column prop="age" label="年龄"  sortable></el-table-column>
            <el-table-column prop="state" label="状态"  sortable>
                <template scope="scope">
                    <span v-if="scope.row.state == 1" style="color: #056c31;">正常</span>
                    <span v-else-if="scope.row.state == 0" style="color: #ccca04;">审核</span>
                    <span v-else style="color: #ff2424;">禁用</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleedit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handledel(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchremove" :disabled="this.sels.length===0">批量删除</el-button>
            <!--
                el-pagination: 分页组件
                    必须通过total属性与当前组件的属性进行绑定，查询到数据后，不但要给table绑定变量赋值，也要给这个total赋值
                    page-size: 表示每页的行数，默认是10
                    current-change： 当当前页码发生改变时触发事件（翻页）
                        在这个事件内，修改请求参数，发送到后端接口
            -->
            <el-pagination layout="prev, pager, next" @current-change="handlecurrentchange" :page-size="10" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" :visible.sync="employeeformvisible" :close-on-click-modal="false">
            <el-form :model="employeeform" label-width="80px" :rules="employeeformrules" ref="employeeform">
                <el-form-item label="名字" prop="username">
                    <el-input v-model="employeeform.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="employeeform.email" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="employeeform.age" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="职位">
                <el-select v-model="employeeform.job_id" placeholder="请选择">
                    <el-option v-for="e in managerjobs" :key="e.id"
                               :label="e.name" :value="e.id"></el-option>
                </el-select>
            </el-form-item>
                <el-form-item label="所属部门" prop="parent_id">
                    <el-select v-model="employeeform.parent_id" placeholder="请选择">
                        <el-option v-for="dept in employeeoptions" :key="dept.id"
                                   :label="dept.name" :value="dept.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="employeeformvisible = false">取消</el-button>
                <el-button type="primary" @click.native="submitform" :loading="submitloading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import nprogress from 'nprogress'
    import { getuserlistpage, removeuser, batchremoveuser, edituser, adduser } from '../../api/api';

    export default {
        data() {
            //表单验证
            let strLenght = (rule, value, callback) => {
                if(value.length < 3 || value.length > 5 ){
                    callback(new Error("部门必须3-5位"))
                }callback()
            }
            //表单验证
            let deptSnUnique =(rule, value, callback)=>{
                this.$http.get("/employee/findBySn?sn="+value+"&id="+this.employeeform.id).then(res=>{
                    console.debug(res)
                    if(res.data.success){
                        callback();
                    }else{
                        callback(new Error(res.data.msg))
                    }
                })
            }
            return {
                filters: {				//高级查询的条件
                    username: ''
                },
                employeeoptions:[],	//部门下拉框的选项数组
                managerOptions:[],
                managerjobs:[],     //职位
                employees: [],		//表格数据
                total: 0,				//总行数
                page: 1,				//当前页码
                listloading: false,		//表格是否正在加载数据
                sels: [],				//列表选中行
                employeeformvisible: false, //编辑界面是否显示
                submitloading: false,
                employeeformrules: {		//表单验证的规则
                    username: [
                        { required: true, message: '姓名', trigger: 'blur' },
                        {validator: strLenght, trigger: 'blur'}
                    ],
                    // sn: [
                    //     { required: true, message: '请输入部门编号!', trigger: 'blur' },
                    //     {validator: deptSnUnique, trigger: 'blur'}
                    // ]
                },
                //编辑界面数据[与上面的表单输入框进行了双向绑定：用户在输入框中输入了内容，那么这里的对象的属性值也会随之改变]
                employeeform: {
                    id: null,
                    username: '',
                    email: '',
                    age: '',
                    state: 0,
                    job_id: null
                }
            }
        },
        methods: {
            //性别显示转换
            formatsex: function (row, column) {
                return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            },
            //分页组件
            handlecurrentchange(val) {
                this.page = val;
                this.loaddata();
            },
            //页面挂载完毕后加载数据
            loaddata() {
                let para = {
                    pageNo: this.page,
                    username: this.filters.username
                };
                //开启模态框
                this.listLoading = true;
                //NProgress.start();
                this.$http.patch("/employee", para).then(res => {
                    //NProgress.start();
                    console.debug(res)
                    this.total = res.data.data.total;
                    this.employees = res.data.data.rows;
                    this.listLoading = false;
                })
            },
            //删除
            handledel: function (id) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listloading = true;
                    //发送请求
                    this.$http.delete("/employee/" + id).then(res => {
                        console.debug(res)
                        this.listloading = false;
                        let {success,msg} = res.data  //解构表达式
                        if(success){
                            //提示
                            this.$message.success(msg)
                            //重新加载数据
                            this.loaddata()
                        }else{
                            //提示
                            this.$message.error(msg)
                        }
                    })

                })
            },
            //显示编辑界面
            handleedit: function (index, row) {
                this.employeeformvisible = true;		//弹出模态框
                //object.assign({}, row)
                //给employeeform赋值，由于它与上面表单中进行了双向绑定，一旦赋值后，表单输入框中就能够自动回显数据了
                //有的时候，这里还需要通过id到后端去查询数据来进行回显数据【当分页查询数据时没有查询全部列的时候，有些属性的数据为null】
                // this.$http.get("/employee/"+ row.id).then(res=>{
                //    this.employeeform = res.data
                // })
                this.employeeform = Object.assign({}, row)
            },
            //显示新增界面
            handleadd: function () {
                this.employeeformvisible = true;
                this.employeeform = {
                    id: null,
                    username: '',
                    email: '',
                    age: '',
                    state: 0,
                    job_id: null
                };
            },
            //新增或者编辑时提交表单
            submitform: function () {
                this.$refs.employeeform.validate((valid) => {
                    if (valid) {
                        this.submitloading = true;
                        //发送请求
                        this.$http.put("/employee", this.employeeform).then(res => {
                            let {success,msg} = res.data  //解构表达式
                            if(success){
                                this.$message.success(msg)
                                this.submitloading = false;//提交表单
                                //this.$refs['employeeform'].resetfields();//重置表单
                                this.employeeformvisible = false;			//关闭模态框
                                this.loaddata()		//重新加载数据
                            }else{
                                this.$message.error(msg)
                            }
                        })
                    }
                });
            },
            selschange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchremove: function () {
                // var ids = [];
                // for(let i=0;i<this.sels.length;i++){
                //     ids.push(this.sels[i].id);
                // }
                // map表示遍历一个数组，里面是一个箭头函数：函数内部表示获取对象的id属性进行返回出来，放入一个数组中
                var ids = this.sels.map(dept => dept.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    /**
                     * 发送请求
                     * 	传递多个id有两个方式：
                     * 		可以将数组使用join方法拼接逗号，形成一个字符串来进行传递，后端可以采用路径变量接收；
                     * 		可以将数组直接传递，后端使用List<Long>来接收，但是这种只能是POST请求才行；
                     */
                    this.$http.post("/employee/batch", ids).then(res => {
                        this.listLoading = false;
                        let {success,msg} = res.data  //解构表达式
                        if(success){
                            //提示
                            this.$message.success(msg)
                            //重新加载数据
                            this.loaddata()
                        }else{
                            //提示
                            this.$message.error(msg)
                        }
                    })
                })
            }
        },
        mounted() {
            this.loaddata();
            //页面挂载完毕后，查询部门列表，用来做为上级部门下拉框的选项
            this.$http.post("/department",{}).then(res => {
                this.employeeoptions = res.data
            })
            //查询员工
            this.$http.get("/employee/findByJob_id/5").then(res => {
                this.managerOptions = res.data
            })
            //查询职位
            this.$http.get("/employee/managerjobs/3").then(res => {
                this.managerjobs = res.data
            })
        }
    }

</script>

<style scoped>

</style>